import sys
import sys
from tkinter import Tk, filedialog
from PyPDF2 import PdfReader, PdfWriter
from path import Path

from pdf_white_cut.logger import logger
from pdf_white_cut.worker import cut_pdf


def split_pdf_pages(input_pdf_path):
    # 同目录创建文件夹 input_pdf_path 是字符
    pdf_path =  Path(input_pdf_path)
    output_dir = pdf_path.parent / pdf_path.name + "_auto_cut"
    # 如果文件夹不存在，创建文件夹
    if not output_dir.exists():
        output_dir.makedirs()
    # 如果存在，删除
    else:
        output_dir.rmtree_p()
        output_dir.makedirs()



    # 打开原始 PDF 文件
    reader = PdfReader(input_pdf_path)
    num_pages = len(reader.pages)

    # 遍历每一页
    for page_num in range(num_pages):
        page = reader.pages[page_num]
        page.compress_content_streams()
        writer = PdfWriter()
        writer.add_page(page)  # 将该页添加到新的PDF写入对象

        # 定义输出文件名
        output_pdf_path = output_dir / f"page_{page_num + 1}.pdf"
        print(f"正在保存 {output_pdf_path} ...")
        # 定义裁剪后的PDF文件名
        cut_result_pdf = output_dir / f"page_{page_num + 1}_cut.pdf"

        # 保存单页PDF
        with open(output_pdf_path, "wb") as output_pdf:
            writer.write(output_pdf)

        print(f"保存 {output_pdf_path} 成功")

        # 开始处理边界问题
        logger.remove()
        cut_pdf(output_pdf_path, cut_result_pdf, 2)
        # 删除原始的PDF文件
        output_pdf_path.remove()


# 示例调用
# input_pdf_path = "/Users/brioal/Desktop/转移网络绘图.pdf"
# split_pdf_pages(input_pdf_path)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        first_argument = sys.argv[1]
        print(f"The first argument is: {first_argument}")
        split_pdf_pages(first_argument)
    else:
        # 弹出文件选择框
        root = Tk()
        root.withdraw()  # 隐藏主窗口
        file_path = filedialog.askopenfilename(
            title="选择PDF文件",
            filetypes=[("PDF files", "*.pdf")]
        )
        if file_path:
            split_pdf_pages(file_path)
        else:
            print("未选择文件。")
